package com.atguigu.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.SubjectData;
import com.atguigu.eduservice.service.EduSubjectService;
import com.atguigu.exceptionhandler.DIYException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;

@AllArgsConstructor
@NoArgsConstructor
public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {
    private EduSubjectService eduSubjectService;
    @Override
    //读取Excel内容
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
                if(subjectData==null){
                    throw new DIYException(400,"文件内容为空");
                }

                //判断 添加一级分类
                EduSubject oneEduSubject = exitOneEduSubject(eduSubjectService, subjectData.getOneSubjectName());
                if (oneEduSubject==null){
                    oneEduSubject = new EduSubject();
                    oneEduSubject.setTitle(subjectData.getOneSubjectName());
                    oneEduSubject.setParentId("0");
                    eduSubjectService.save(oneEduSubject);
                }

                //判断  添加二级分类
                String pid =oneEduSubject.getId();
                EduSubject twoEduSubject = exitTwoEduSubject(eduSubjectService, subjectData.getTwoSubjectName(), pid);

                if (twoEduSubject==null){
                    twoEduSubject = new EduSubject();
                    twoEduSubject.setParentId(pid);
                    twoEduSubject.setTitle(subjectData.getTwoSubjectName());
                    eduSubjectService.save(twoEduSubject);
                }

    }
    //查询一级分类 没有parent_id就是一级分类
    public EduSubject exitOneEduSubject(EduSubjectService eduSubjectService,String name){
        QueryWrapper queryWrapper =new QueryWrapper();
        queryWrapper.eq("title",name);
        queryWrapper.eq("parent_id",0);
        EduSubject one = eduSubjectService.getOne(queryWrapper);
        return one;
    }
    //查询二级分类 有parent_id就是二级分类
    public EduSubject exitTwoEduSubject(EduSubjectService eduSubjectService,String name,String pid){
        QueryWrapper queryWrapper =new QueryWrapper();
        queryWrapper.eq("title",name);
        queryWrapper.eq("parent_id",pid);
        EduSubject two = eduSubjectService.getOne(queryWrapper);
        return two;
    }
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
